//
//  BIDMenuViewController.m
//  党务通
//
//  Created by mal on 13-11-15.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#define ITEM_SPACING 0
#define LINE_SPACING 15
#define TOP_SPACING 10
#define LEFT_SPACING 15
#define RIGHT_SPACING 5
//菜单图标的宽高
#define ICON_WIDTH 70
#define ICON_HEIGHT 105

#define CELL_IDENTIFIER @"cellIdentifier"

#import "BIDMenuViewController.h"
#import "BIDCollectionCellView.h"
#import "AppDelegate.h"

@interface BIDMenuViewController ()

@end

@implementation BIDMenuViewController

@synthesize imgArr;
@synthesize titleArr;
@synthesize menuCollectionView;
@synthesize cornerMarkCount;
@synthesize cornerCountsAndIndexArr;

@synthesize bgImgView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        imgArr = [[NSMutableArray alloc] initWithCapacity:1];
        titleArr = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTheme];
	// Do any additional setup after loading the view.
    _menuArr = @[];
    if([UIDevice currentDevice].systemVersion.doubleValue>=7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect ownFrame = CGRectMake(0, 0, screenSize.width, screenSize.height-64);
    self.view.frame = ownFrame;
    //设置背景颜色
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(ICON_WIDTH, ICON_HEIGHT)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    flowLayout.sectionInset = UIEdgeInsetsMake(TOP_SPACING, LEFT_SPACING, 5, RIGHT_SPACING);
    flowLayout.minimumInteritemSpacing = (screenSize.width-LEFT_SPACING-RIGHT_SPACING-4*ICON_WIDTH)/3;
    flowLayout.minimumLineSpacing = LINE_SPACING;
    CGRect collectionViewFrame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.menuCollectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayout];
    [self.view addSubview:menuCollectionView];
    [self.menuCollectionView setBackgroundColor:[UIColor clearColor]];
    //注册cell
    [self.menuCollectionView registerClass:[BIDCollectionCellView class] forCellWithReuseIdentifier:CELL_IDENTIFIER];
    
    self.menuCollectionView.delegate = self;
    self.menuCollectionView.dataSource = self;

    //添加背景
    NSString *viewBgImgName = @"main_bg.png";
    bgImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:viewBgImgName]];
    bgImgView.frame = self.menuCollectionView.frame;
    self.menuCollectionView.backgroundView = bgImgView;
}

//
- (int)getCornerCountByIndex:(int)index
{
    int count = 0;
    for(int i=0; i<cornerCountsAndIndexArr.count; i++)
    {
        NSDictionary *dictionary = [cornerCountsAndIndexArr objectAtIndex:i];
        NSNumber *value = [dictionary objectForKey:@"index"];
        if([value intValue]==index)
        {
            value = [dictionary objectForKey:@"count"];
            count = [value intValue];
            break;
        }
    }
    return count;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    self.imgArr = nil;
    self.titleArr = nil;
    self.menuCollectionView = nil;
    self.navController = nil;
    self.cornerCountsAndIndexArr = nil;
}

//获得角标的数目
- (void)getCornerMarkCount:(NSArray*)arr
{
    //app icon 角标应该显示的数目
    __block int appIconBadge = 0;
    //
    cornerCountsAndIndexArr = [[NSMutableArray alloc] initWithCapacity:[arr count]];
    dispatch_group_t group = dispatch_group_create();
    for(int i=0; i<arr.count; i++)
    {
        NSDictionary *dictionary = [arr objectAtIndex:i];
        NSNumber *indexValue = [dictionary objectForKey:@"index"];
        NSString *strURL = [dictionary objectForKey:@"url"];
        strURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], strURL];
        NSString *strPost = dictionary[@"param_request"];
        dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
            NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc] initWithCapacity:1];
            int rev = [BIDDataCommunication getDataWithURL:strURL andPost:strPost toDictionary:tempDictionary];
            NSNumber *countValue = [NSNumber numberWithInt:0];
            if(rev==1)
            {
                NSString *strKey = dictionary[@"param_response"];
                countValue = tempDictionary[strKey];
                if(!countValue) countValue = @0;
            }
            NSDictionary *dictionary1 = @{@"index":indexValue, @"count":countValue};
            
            appIconBadge += [countValue intValue];
            //
            [cornerCountsAndIndexArr addObject:dictionary1];
        });
    }
    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //arr.count==6说明当前界面为主界面，主界面的角标数量的总和就代表app icon badge的数目
            if(arr.count==6)
            {
                [UIApplication sharedApplication].applicationIconBadgeNumber = appIconBadge;
            }
            //
            [menuCollectionView reloadData];
        });
    });
}

- (void)backBtnHandler
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setTheme
{}

#pragma mark UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _menuArr.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    BIDCollectionCellView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
    NSDictionary *dic = _menuArr[row];
    NSString *imgName = dic[@"imgName"];
    NSString *strTitle = dic[@"title"];
    UIImageView *imgView = (UIImageView*)[cell viewWithTag:2];
    UILabel *label = (UILabel*)[cell viewWithTag:1];
    label.text = strTitle;
    imgView.image = [UIImage imageNamed:imgName];
    
    int cornerCount = 0;
    for(int i=0; i<cornerCountsAndIndexArr.count; i++)
    {
        NSDictionary *dictionary = [cornerCountsAndIndexArr objectAtIndex:i];
        NSNumber *indexValue = [dictionary objectForKey:@"index"];
        if([indexValue intValue]==row)
        {
            NSNumber *countValue = [dictionary objectForKey:@"count"];
            cornerCount += [countValue intValue];
            [cell adjustNumberLabel:[[NSString alloc] initWithFormat:@"%d", cornerCount]];
            break;
        }
        if(i==cornerCountsAndIndexArr.count-1) cell.numberLabel.hidden = YES;
    }
    return cell;
}
@end
